package cn.rengy.tool.excel;

import cn.rengy.util.ExceptionPrintUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.RegionUtil;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;

import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

@Slf4j
public class SimpleExcelWrite {

    private static void doExport2007(SXSSFWorkbook workbook, List<SheetObject> sheetList) {
        Map<CellStyleObject,CellStyle> cellStyleMap=new HashMap<>();
        for(SheetObject sheetObject:sheetList){
            String sheetName=sheetObject.getSheetName();
            SXSSFSheet sheet=null;
            if(sheetName==null){
                sheet = workbook.createSheet();
            }else{
                sheet = workbook.createSheet(sheetName);
            }
            List<Map<Integer, CellObject>> dataList=sheetObject.getShheetData();
            List<CellRangeAddress> mergeCelllist=sheetObject.getMergeCelllist();
            if(dataList!=null&&dataList.size()>0){
                int size=dataList.size();
                for (int i = 0;i < size; i++) {//写sheet
                    Map<Integer,CellObject> rowData=dataList.get(i);
                    SXSSFRow row = sheet.createRow(i);
                    Iterator<Map.Entry<Integer, CellObject>> iterator=rowData.entrySet().iterator();
                    while(iterator.hasNext()){
                        Map.Entry<Integer, CellObject> entry=iterator.next();
                        int cellIndex=entry.getKey();
                        CellObject cellObject=entry.getValue();
                        SXSSFCell cell = row.createCell(cellIndex);
                        String text=cellObject.getText();
                        CellStyle cellStyle=getCellStyle(cellStyleMap, workbook, cellObject.getCellStyleObject());
                        cell.setCellStyle(cellStyle);
                        if(text!=null&&text.length()>0){
                            cell.setCellValue(text);
                        }
                    }
                }
                //单元格合并
                if(mergeCelllist!=null){
                    for(CellRangeAddress cra:mergeCelllist){
                        sheet.addMergedRegion(cra);
                        RegionUtil.setBorderBottom(BorderStyle.THIN,cra,sheet);
                        RegionUtil.setBorderTop(BorderStyle.THIN,cra,sheet);
                        RegionUtil.setBorderLeft(BorderStyle.THIN,cra,sheet);
                        RegionUtil.setBorderRight(BorderStyle.THIN,cra,sheet);
                    }
                }



            }
        }
    }

    private static CellStyle getCellStyle(Map<CellStyleObject,CellStyle> cellStyleMap,SXSSFWorkbook workbook,CellStyleObject cellStyleObject){
        CellStyle cellStyle=cellStyleMap.get(cellStyleObject);
        if(cellStyle==null){
            cellStyle= createCellStyle( workbook, cellStyleObject);
            cellStyleMap.put(cellStyleObject,cellStyle);
        }
        return cellStyle;
    }
    private static CellStyle createCellStyle(SXSSFWorkbook workbook,CellStyleObject cellStyleObject){
        CellStyle cellStyle=  workbook.createCellStyle();//单元格样式
        Font font = workbook.createFont();
        font.setFontName("宋体");
        cellStyle.setFont(font);
        FontObject fontObject=cellStyleObject.getFontObject();
        //设置字体
        if(font.getFontName()!=null){
            font.setFontName(font.getFontName());
        }
        if(fontObject.getFontHeightInPoints()!=0){
            font.setFontHeightInPoints(fontObject.getFontHeightInPoints());
        }
        if(fontObject.isBold()){
            font.setBold(true);
            font.getFontHeight();
        }
        //设置单元格样式
        if(cellStyleObject.getFillForegroundColor()!=null){
            cellStyle.setFillForegroundColor(cellStyleObject.getFillForegroundColor().getIndex());
            cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        }
        if(cellStyleObject.getHorizontalAlignment()!=null){
            cellStyle.setAlignment(cellStyleObject.getHorizontalAlignment());
        }
        if(cellStyleObject.getVerticalAlignment()!=null){
            cellStyle.setVerticalAlignment(cellStyleObject.getVerticalAlignment());
        }
        if(cellStyleObject.isWrapText()){
            cellStyle.setWrapText(true);
        }

        return cellStyle;
    }

    public static void export2007(OutputStream outputStream, List<SheetObject> sheetList){
        SXSSFWorkbook workbook = new SXSSFWorkbook();
        try {
            doExport2007(workbook,sheetList);
            workbook.write(outputStream);
        } catch (Exception e) {
            log.error(ExceptionPrintUtils.getTrace(e));
        }finally{
            try {
                workbook.close();
            } catch (IOException e) {
                log.error(ExceptionPrintUtils.getTrace(e));
            }

            try {
                outputStream.flush();
                outputStream.close();
            } catch (IOException e) {
                log.error(ExceptionPrintUtils.getTrace(e));
            }
        }
    }
    /**
     * HSSFWorkbook 2003以下版本
     * @param outputStream
     * @param dataList
     */
    public static void export2003(OutputStream outputStream,List<Map<String,Object>> dataList){
        if(dataList!=null&&dataList.size()>0){
            Map<String,Object> cellMap=dataList.get(0);
            //创建工作薄对象
            HSSFWorkbook wb = new HSSFWorkbook();
            int dataLength=dataList.size();
            int sheetMaxLength=65535;
            double d=(double)dataLength/sheetMaxLength;
            int sheetCount=(int)Math.ceil(d);
            for(int k=0;k<sheetCount;k++){
                HSSFSheet sheet =  wb.createSheet();//创建sheet
                int rowStart=k*sheetMaxLength;
                int rowCount=(rowStart+sheetMaxLength)>dataLength?dataLength:(rowStart+sheetMaxLength);
                for (int i = rowStart,rowIndex = 0; i < rowCount; i++) {//写sheet
                    Map<String,Object> data=dataList.get(i);
                    HSSFRow row = sheet.createRow(rowIndex++);//创建行
                    Set<String> keySet=cellMap.keySet();
                    Iterator<String> ite=keySet.iterator();
                    int cellIndex=0;
                    while(ite.hasNext()){
                        HSSFCell cell = row.createCell(cellIndex++);
                        Object value=data.get(ite.next());
                        cell.setCellValue(value==null?"":value.toString());
                    }
                }
            }

            try {
                wb.write(outputStream);
            } catch (IOException e) {
            }finally{
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                }
                try {
                    wb.close();
                } catch (IOException e) {
                }

            }
        }
    }
}
